﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace MinistryStandardPlatformBusiness.MessagePool.Entity
{
    class JsonHelper
    {

        #region JsonHelper
        /// <summary>
        /// JSON序列化
        /// </summary>
        public static string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }

        /// <summary>
        /// JSON反序列化
        /// </summary>
        /// 
        public static T JsonDeserialize<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }

        #endregion

        /// <summary>
        /// 实时信息反序列化
        /// </summary>
        /// <param name="strObj"></param>
        /// <returns></returns>
        public static LatestGpsInfo DeserializeLatestGpsInfo(string strObj)
        {
            if (strObj == "" || strObj == null)
                return null;

            JObject jo = JObject.Parse(strObj);
            LatestGpsInfo temp = new LatestGpsInfo();
            temp.Altitude = jo["altitude"].ToString();
            temp.DevSpeed = jo["devSpeed"].ToString();
            temp.Direction = jo["direction"].ToString();
            temp.Distance = jo["distance"].ToString();
            temp.GpsDistance = jo["gpsDistance"].ToString();
            temp.Latitude = jo["latitude"].ToString();
            temp.Longitude = jo["longitude"].ToString();
            temp.Oil = jo["oil"].ToString();
            temp.Memo = jo["memo"].ToString();
            try
            {
                temp.AttachOil = jo["attachOil"].ToString();
            }
            catch (Exception)
            {
                temp.AttachOil = temp.Oil;
            }
            temp.SatelliteNum = jo["satelliteNum"].ToString();
            temp.SignalStrength = jo["signalStrength"].ToString();
            temp.SimId = jo["simId"].ToString();
            temp.Speed = jo["speed"].ToString();
            temp.UpTime = jo["upTime"].ToString();
            temp.WarnSign = jo["warnSign"].ToString();
            temp.StatusSign = jo["statusSign"].ToString();
            try
            {
                  temp.battery = jo["battery"].ToString();
            }
            catch (Exception)
            {
                temp.battery = "";
            }
            return temp;
        }
        /// <summary>
        /// 报警解析
        /// </summary>
        /// <param name="strObj"></param>
        /// <returns></returns>
        public static GpsWarn DeserializeGpsWarn(string strObj)
        {
            if (strObj == "" || strObj == null)
                return null;

            JObject jo = JObject.Parse(strObj);
            GpsWarn gp = new GpsWarn();
            try
            {
                gp.SimId = jo["simId"].ToString();
                gp.Latitude=jo["latitude"].ToString();
                gp.Longitude = jo["longitude"].ToString();
                gp.WarnType = jo["warnType"].ToString();
                gp.WarnStartTime = jo["warnStartTime"].ToString();
                LngLatPoi mLngLatPoi = new LngLatPoi();

            }
            catch (Exception)
            {
                MinistryStandardPlatformBusiness.Helper.Log.WriteLog("gpsWarnError",strObj);
                gp = null;
            }

            return gp;


        }

        public static T JsonStrToObject<T>(string jsonStr)
        {
            T obj = Activator.CreateInstance<T>();  //注意 要有T类型要有无参构造函数
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr)))
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }

        public static string ListToJsonStr<T>(List<T> list)
        {
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(list.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, list);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch
            {
                return null;
            }
        }

        public static string ObjectToJsonStr<T>(T obj)
        {
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, obj);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch
            {
                return null;
            }
        }

        #region json 转换为datatable 测试通过

        public static DataTable JsonToDataTable(string strJson)
        {
            //取出表名   
            var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名   
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));

            //获取数据   
            rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split(',');

                //创建表   
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        var dc = new DataColumn();
                        string[] strCell = str.Split(':');
                        string header = strCell[0];
                        if (header.ToString().Contains("\""))
                        {
                            header = header.Replace("\"", "");
                        }
                        dc.ColumnName = header;
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }

                //增加内容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    string s = null;
                    s = strRows[r].Split(':')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                  
                    if (strRows[r].Split(':').Length > 2)
                    {//时间的特别处理
                        for (int ii = 2; ii < strRows[r].Split(':').Length; ii++)
                        {
                            s +=":"+ strRows[r].Split(':')[ii].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                        }
                    }
                    dr[r] = s;
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }

            return tb;
        }

        public static string JsonTableToJson(string strJson)
        {
            //取出表名   
            var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            //去除表名   
            if (strJson.Length > 4)
            {
                strJson = strJson.Substring(2, strJson.Length - 4);
                //获取数据   
                rg = new Regex(@"(?<={)[^}]+(?=})");
                MatchCollection mc = rg.Matches(strJson);
                if (mc.Count > 0)
                {
                    return strJson;
                }
                else
                {
                    return "";
                }
            }
            else
            {
                return "";
            }
        }

        public static List<string> getListSingleStr(string strJson)
        {
            List<string> ls = new List<string>();
            var rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split(',');
                foreach (string str in strRows)
                {
                    string[] strCell = str.Split(':');
                    string bd = strCell[1];
                    if (bd.ToString().Contains("\""))
                    {
                        bd = bd.Replace("\"", "");
                    }

                    ls.Add(bd);
                }
            }
            return  ls;
        }
        #endregion


        public static DataTable JsonToDataTableNew(string strJson)
        {
            //取出表名   
            var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名   
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));

            //获取数据   
            rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split(',');

                //创建表   
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        var dc = new DataColumn();
                        string[] strCell = str.Split(':');
                        string header = strCell[0];
                        if (header.ToString().Contains("\""))
                        {
                            header = header.Replace("\"", "");
                        }
                        dc.ColumnName = header;
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }

                //增加内容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    string s = null;
                    s = strRows[r].Split(':')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                    dr[r] = s;
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }

            return tb;
        }
    }
}
